/**
 * 
 */
package com.rangers.auth.base.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.rangers.auth.base.db.MenuDbAccess;
import com.rangers.auth.base.details.BriefMenu;
import com.rangers.auth.base.details.MenuTypeEnum;

/**
 * 菜单sevice
 * 
 * @version 1.0
 * @author fuhw
 * @date 2017年8月18日 下午12:22:57
 */
@Service
@SuppressWarnings("rawtypes")
public class MenuServiceHandler<T extends BriefMenu,ID extends Serializable,ACCESS extends MenuDbAccess<T, ID>> implements MenuService<T, ID,ACCESS> {

	private final ACCESS access;

	@Autowired
	public MenuServiceHandler(ACCESS MenuRepo) {
		super();
		this.access = MenuRepo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rangers.auth.base.service.MenuService#get(java.io.Serializable)
	 */
	@Override
	public T get(ID id) {
		Assert.notNull(id, "the token of object must be not null");
		return access.findOne(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rangers.auth.base.service.MenuService#list()
	 */
	@Override
	public List<T> list() {
		return (List<T>) access.findAll();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.rangers.auth.base.service.MenuService#create(com.rangers.auth.base.
	 * entity.BriefMenu)
	 */
	@Override
	@Transactional
	public T create(T entity) {
		argumentValidate(true, entity);
		return access.save(entity);
	}

	@SuppressWarnings("unchecked")
	private void argumentValidate(boolean isAdd, T entity) {
		Assert.notNull(entity, "the entity for create must be not null");
		if (entity.getType().equals(MenuTypeEnum.LINK)) {
			Assert.hasText(entity.getLink(), "LINK类型的菜单的值不能为空");
		} else if (entity.getType().equals(MenuTypeEnum.PERMISSION)) {
			Assert.hasText(entity.getPermissions(), "PERMISSION类型的菜单的值不能为空");
		}
		Assert.isTrue(!access.existsByName(entity.getName()), String.format("菜单名[%s]已存在", entity.getName()));
		if (!isAdd && entity.getParentId() != null) {
			Assert.isTrue(access.exists((ID) entity.getParentId()), "菜单的父级不存在");
			Assert.isTrue(!entity.getId().equals(entity.getParentId()), "菜单的父级不能为自身");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.rangers.auth.base.service.MenuService#update(com.rangers.auth.base.
	 * entity.BriefMenu)
	 */
	@Override
	@Transactional
	public T update(T entity) {
		argumentValidate(true, entity);
		return access.save(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.rangers.auth.base.service.MenuService#delete(java.io.Serializable)
	 */
	@Override
	public void delete(ID id) {
		access.delete(id);
	}
}
